package com.mifengkong.im.huanxin;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.hyphenate.EMError;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.helpdesk.callback.Callback;
import com.hyphenate.helpdesk.easeui.util.IntentBuilder;
import com.mifengkong.frtools.util.FRLog;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.im.Constant;
import com.mifengkong.im.DemoHelper;
import com.mifengkong.im.MessageHelper;
import com.mifengkong.im.Preferences;
import com.mifengkong.im.R;
import com.mifengkong.im.ui.ChatActivity;

import java.util.Random;


/**
 * Created by mifeng on 2016/7/7.
 * 用于环信登录或者注册时使用的
 */
public class EMChatLoginUtils {

    private static int selectedIndex = Constant.INTENT_CODE_IMG_SELECTED_DEFAULT;

    public boolean progressShow;
    public ProgressDialog progressDialog;
    private static EMChatLoginUtils mInstance;

    public static EMChatLoginUtils getInstance() {
        if (mInstance == null) {
            // 用来解决多并发的问题
            synchronized (EMChatLoginUtils.class) {
                if (mInstance == null) {
                    mInstance = new EMChatLoginUtils();
                }
            }
        }
        return mInstance;
    }


    private ProgressDialog getProgressDialog(Activity activity) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(activity);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    progressShow = false;
                }
            });
        }
        return progressDialog;
    }

    public String getRandomAccount() {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) // 字符串
            {
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
                val += (char) (choice + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(charOrNum)) // 数字
            {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val.toLowerCase();
    }


    /**
     * 创建随机账号，并且登录到服务器
     */
    public void createRandomAccountAndLoginChatServer(final Activity activity, ChatInfoBean chatInfoBean) {
        // 自动生成账号
        String randomAccount = TextUtils.isEmpty(chatInfoBean.getUserName()) ? getRandomAccount() : chatInfoBean.getUserName();
        String userPwd = Constant.DEFAULT_ACCOUNT_PWD;
        progressDialog = getProgressDialog(activity);
        progressDialog.setMessage("正在连接...");
        progressDialog.show();
        //注册账号并登录
        chatInfoBean.setUserName(randomAccount);
        chatInfoBean.setPassword(userPwd);
        createAccountToServer(activity, chatInfoBean);
    }


    //注册用户
    public void createAccountToServer(final Activity activity, final ChatInfoBean chatInfoBean) {
        final String userName = chatInfoBean.getUserName();
        final String password = chatInfoBean.getPassword();
        ChatClient.getInstance().register(userName, password, new Callback() {
            @Override
            public void onSuccess() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //登录环信服务器
                        loginHuanxinServer(activity, chatInfoBean);
                    }
                });
            }

            @Override
            public void onError(final int errorCode, final String s) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        FRLog.error("errorCode-------->" + errorCode + "\nmessage-------->" + s);
                        if (errorCode == EMError.USER_ALREADY_EXIST) {
                            //用户已存在，登录
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //登录环信服务器
                                    loginHuanxinServer(activity, chatInfoBean);
                                }
                            });
                            return;
                        }
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (errorCode == EMError.NETWORK_ERROR) {
                            FRToast.showToastSafe("网络不可用");
                        } else if (errorCode == EMError.USER_AUTHENTICATION_FAILED) {
                            FRToast.showToastSafe("无开放注册权限");
                        } else if (errorCode == EMError.USER_ILLEGAL_ARGUMENT) {
                            FRToast.showToastSafe("用户名非法");
                        } else {
                            FRToast.showToastSafe("连接失败，您还可以拨打电话客服或者重新安装APP");
                        }
                    }
                });
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }


    /**
     * 登录环信的服务端
     */
    public void loginHuanxinServer(final Activity activity, final ChatInfoBean chatInfoBean) {
        ChatClient.getInstance().login(chatInfoBean.getUserName(), chatInfoBean.getPassword(), new Callback() {
            @Override
            public void onSuccess() {
                toChatActivity(activity, chatInfoBean);
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onError(int i, final String s) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        Toast.makeText(activity,
                                activity.getResources().getString(R.string.is_contact_customer_failure_seconed) + s,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

    /**
     * 进去聊天界面
     */
    public void toChatActivity(final Activity activity, final ChatInfoBean chatInfoBean) {

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    progressDialog = getProgressDialog(activity);
                    progressDialog.setMessage("正在连接...");
                    progressDialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (!activity.isFinishing())
                    progressDialog.dismiss();
                // 进入主页面
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.INTENT_CODE_IMG_SELECTED_KEY, selectedIndex);
                Intent intent = new IntentBuilder(activity)
                        .setTargetClass(ChatActivity.class)
                        .setVisitorInfo(MessageHelper.createVisitorInfo(chatInfoBean.getUserName(), chatInfoBean.getUserPhone()))
                        .setServiceIMNumber(Preferences.getInstance().getCustomerAccount())
                        .setShowUserNick(true)
                        .setBundle(bundle)
                        .setTitleBgColor(chatInfoBean.getTitleBgColor())
                        .setTitleName(chatInfoBean.getTitleName())
                        .build();
                activity.startActivity(intent);

                DemoHelper.getInstance().updateUserAvator(chatInfoBean.getUserAvatar());
            }
        });
    }

    public void chatWithService(final Activity activity, int titleBgColor) {
        chatWithService(activity, titleBgColor, null, null, null, null);
    }

    public void chatWithService(final Activity activity, int titleBgColor, String userName, String userPhone, String userAvatar, String titleName) {
        ChatInfoBean chatInfoBean = new ChatInfoBean(userName, userPhone, titleName, titleBgColor, userAvatar);
        com.hyphenate.helpdesk.easeui.util.Preferences.getInstance().clearMessageSize();
        if (ChatClient.getInstance().isLoggedInBefore()) {
            //已经登录，可以直接进入会话界面
            toChatActivity(activity, chatInfoBean);
        } else {
            //未登录，需要登录后，再进入会话界面
            createRandomAccountAndLoginChatServer(activity, chatInfoBean);
        }
    }


}
